import { Draw } from "ol/interaction";
import { createBox } from "ol/interaction/Draw";
import VectorSource from "ol/source/Vector";
import VectorLayer from "ol/layer/Vector";

/**
 * 绘制图形
 * @param {*} type
 */
export function drawGtaph(map, endCallback) {
  const source = new VectorSource({ wrapX: false });
  const vector = new VectorLayer({
    source: source,
  });
  let draw = null;
  map.addLayer(vector);
  return (type) => {
    draw && map.removeInteraction(draw);
    let geometryFunction = undefined;
    /// 扩展实现绘制矩形
    if (type === "Rect") {
      type = "Circle";
      geometryFunction = createBox();
    }
    draw = new Draw({
      source: source,
      type: type,
      geometryFunction,
    });

    ///绘制完成
    draw.on("drawend", function (event) {
      var feature = event.feature;
      var geometry = feature.getGeometry();
      // 可以根据需要对图形进行处理，例如获取坐标等
      console.log(geometry.getCoordinates());
      endCallback(geometry.getCoordinates(), draw);
    });
    map.addInteraction(draw);
  };
}
